package com.lambo.maven.core.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    /**
     * MD5数字签名
     *
     * @param data 数据.
     * @return md5值 .
     * @throws Exception 异常.
     */
    public static String md5Digest(byte[] data) {
        if (null == data) {
            return null;
        }
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(data);
            return bytesToHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * sha1自满.
     * @param data 原生数据.
     * @return sha1签名.
     */
    public static String sha1Digest(byte[] data) {
        try {
            MessageDigest messagedigest = MessageDigest.getInstance("SHA1");
            return bytesToHex(messagedigest.digest(data));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA1 not exists", e);
        }
    }

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 方法一：
     * byte[] to hex string
     *
     * @param bytes 数据流.
     * @return 16进制数据.
     */
    private static String bytesToHex(byte[] bytes) {
        // 一个byte为8位，可用两个十六进制位标识
        char[] buf = new char[bytes.length * 2];
        int a;
        int index = 0;
        for(byte b : bytes) { // 使用除与取余进行转换
            if(b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }
            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }
        return new String(buf);
    }
}
